package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加小视频
     *
     * @param pojo
     */
    @Override
    public void add(Video pojo) {
        //1. 设置创建
        pojo.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(pojo);
    }

    /**
     * 小视频分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPage(Long page, Long pageSize) {
        //1. 构建条件
        Query query = new Query();
        //2. 总数
        long total = mongoTemplate.count(query, Video.class);
        //3. 总数>0
        List<Video> videoList = new ArrayList<>();
        if(total > 0) {
            //4. 设置分页参数
            query.skip((page-1)*pageSize).limit(pageSize.intValue());
            //5. 设置排序
            query.with(Sort.by(Sort.Order.desc("created")));
            //6. 查询
            videoList = mongoTemplate.find(query, Video.class);
        }
        //7. 构建pageResult返回
        return PageResult.pageResult(page, pageSize, videoList, total);
    }
}
